package com.hdu.h_health.model;

import android.content.Context;
import android.text.TextUtils;

import com.hdu.h_health.bean.Comment;
import com.hdu.h_health.bean.Secret;
import com.hdu.h_health.bean.User;
import com.hdu.h_health.utils.CommonUtils;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * 心事模型层
 * Created by 612 on 2016/3/22.
 */
public class SecretModel extends BaseModel {

    private static SecretModel secretModel = new SecretModel();

    public static SecretModel getInstance() {
        return secretModel;
    }

    private final int LIMIT = 6;// 每页的数据是6条

    //获得所有心事
    public void getAllSecret(final Context context, final int page, FindListener<Secret> findListener) {
        BmobQuery<Secret> query = new BmobQuery<Secret>();
        query.order("-createdAt");
        query.setLimit(LIMIT);//每次查询的心事帖子数
        query.setSkip(page * LIMIT);//从第几页开始
        query.include("author");
        query.findObjects(context, findListener);
    }

    //获取指定用户的心事
    public void getSecret(final Context context, final int page, User user, FindListener<Secret> findListener) {
        BmobQuery<Secret> query = new BmobQuery<Secret>();
        query.addWhereEqualTo("author", user);
        query.order("-createdAt");
        query.setLimit(LIMIT);//每次查询的心事帖子数
        query.setSkip(page * LIMIT);//从第几页开始
        query.include("author");
        query.findObjects(context, findListener);
    }

    //发表心事(没有图片)
    public void publishSecret(final Context context, String content, SaveListener saveListener) {
        if (TextUtils.isEmpty(content)) {
            CommonUtils.showToast(context, "内容不能为空");
            return;
        }
        User user = getCurrentUser();
        Secret secret = new Secret();
        //建立心事与作者的一对一的关系
        secret.setAuthor(user);
        secret.setContent(content);
        secret.setLove(0);
        secret.setShare(0);
        secret.setComment(0);
        secret.setIsPass(true);
        secret.save(context, saveListener);
    }

    //添加心事与评论的关系
    public void addCommentRelation(Context context, Secret secret, Comment comment) {
        BmobRelation relation = new BmobRelation();
        relation.add(comment);
        secret.setCommentRe(relation);
        secret.update(context, new UpdateListener() {
            @Override
            public void onSuccess() {
                CommonUtils.showLog("心事与评论关系添加成功！");
            }

            @Override
            public void onFailure(int i, String s) {
                CommonUtils.showLog("心事与评论关系添加成功！" + i + s);
            }
        });
    }
}
